package plp.functional2.concurrency;

import java.util.ArrayList;
import java.util.List;

import plp.expressions2.expression.Expressao;
import plp.expressions2.expression.Id;
import plp.functional2.primitive.Message;

/**
 * Keeps all the messages exchanged between process.
 * @author Airton
 *
 */
public class MailBox {

	private List<Message> messages;
	private static MailBox mailBox = null;

	private MailBox() {
		super();
		messages = new ArrayList<Message>();
	}

	public static synchronized MailBox getInstance(){
		if (mailBox == null) {
			mailBox = new MailBox();
		}
		
		return mailBox;
	}

	public void addMessage(Message message){
		messages.add(message);System.out.println("### MsgSize = "+ messages.size() + " ###");
	}

	public synchronized Message getMessage(Id processReceiver, List<Id> pattern){
		Message messageToRemove = null;
		int i =0;
		if(!messages.isEmpty()){
			for (Message message: messages) {
				List<Expressao> msgPattern = message.getPattern();
				if (message.getIdProcessReceiver().equals(processReceiver) 
						&& msgPattern.size() == pattern.size()
						&& msgPattern.get(0).equals(pattern.get(0))) {
					messageToRemove = message;
					messages.remove(i);
					break;
				}
				i++;
			}
		}

		return messageToRemove;
	}
}
